package com.mxprojects.io
{
	import com.mxprojects.gui.Styles;
	
	import flash.display.DisplayObjectContainer;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.net.URLRequest;

	public class StylesImageParser
	{
		private var objectToSet:DisplayObjectContainer;
		private var cssObject:Object;
		private var imgLoader:Loader = new Loader();
		
		public function StylesImageParser(){}
		
		public function load(objectToSet:DisplayObjectContainer, cssStyle:String):void {
			//this will allow css to attach an image to a display object
			var imageToLoad:String = Styles.getCleanValue(cssStyle, "backgroundImage");
			
			var cssObject:Object = Styles.css.getStyle(cssStyle);
			
			//setup the private vars
			this.objectToSet = objectToSet;
			this.cssObject = cssObject;

			//load the image			
	    	imgLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, addImage);
	    	imgLoader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, imageNotFound);
	    	imgLoader.load(new URLRequest(imageToLoad));
	    	
	    	//make sure it doesn't interfer with mouse actions
	    	imgLoader.mouseEnabled = false;
	    				
    		//toss this on top of the object that loaded it
    		if(objectToSet.parent != null){
    			objectToSet.parent.addChildAt(imgLoader, objectToSet.parent.getChildIndex(objectToSet) + 1);
    		}
		}
		
		private function addImage(event:Event):void {
			//if they are stretching the background
			if(cssObject["backgroundStretch"] == "true"){
				//add a name to the image so that we can resize it
				imgLoader.name = "backgroundImage";
				imgLoader.width = objectToSet.width;
				imgLoader.height = objectToSet.height;
				imgLoader.x = objectToSet.x;
				imgLoader.y = objectToSet.y;
			}
			
			//see if there are any offsets
			if(cssObject["backgroundX"] != undefined){
				imgLoader.x = int(cssObject["backgroundX"]);
			}
			
			if(cssObject["backgroundY"] != undefined){
				imgLoader.y = int(cssObject["backgroundY"]);
			}
			
		}
		
		private function imageNotFound(event:IOErrorEvent):void {
			trace("NOT FOUND", event.text);
		}
	}
}